package cn.wolfcdoe.audit.service.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.wolfcdoe.audit.mapper.BusBpmnInfoMapper;
import cn.wolfcdoe.audit.domain.BusBpmnInfo;
import cn.wolfcdoe.audit.service.IBusBpmnInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * 流程定义Service业务层处理
 * 
 * @author zhuo
 * @date 2023-04-16
 */
@Service
public class BusBpmnInfoServiceImpl implements IBusBpmnInfoService 
{
    @Autowired
    private BusBpmnInfoMapper busBpmnInfoMapper;

    @Resource
    private RepositoryService repositoryService;                    //Activiti的资源管理接口

    /**
     * 查询流程定义
     * 
     * @param id 流程定义主键
     * @return 流程定义
     */
    @Override
    public BusBpmnInfo selectBusBpmnInfoById(Long id)
    {
        return busBpmnInfoMapper.selectBusBpmnInfoById(id);
    }

    /**
     * 查询流程定义列表
     * 
     * @param busBpmnInfo 流程定义
     * @return 流程定义
     */
    @Override
    public List<BusBpmnInfo> selectBusBpmnInfoList(BusBpmnInfo busBpmnInfo)
    {
        return busBpmnInfoMapper.selectBusBpmnInfoList(busBpmnInfo);
    }

    /**
     * 新增流程定义
     * 
     * @param busBpmnInfo 流程定义
     * @return 结果
     */
    @Override
    public int insertBusBpmnInfo(BusBpmnInfo busBpmnInfo)
    {
        return busBpmnInfoMapper.insertBusBpmnInfo(busBpmnInfo);
    }

    /**
     * 修改流程定义
     * 
     * @param busBpmnInfo 流程定义
     * @return 结果
     */
    @Override
    public int updateBusBpmnInfo(BusBpmnInfo busBpmnInfo)
    {
        return busBpmnInfoMapper.updateBusBpmnInfo(busBpmnInfo);
    }

    /**
     * 批量删除流程定义
     * 
     * @param ids 需要删除的流程定义主键
     * @return 结果
     */
    @Override
    public int deleteBusBpmnInfoByIds(Long[] ids)
    {
        return busBpmnInfoMapper.deleteBusBpmnInfoByIds(ids);
    }

    /**
     * 删除流程定义信息
     * 
     * @param id 流程定义主键
     * @return 结果
     */
    @Override
    public int deleteBusBpmnInfoById(Long id)
    {
        //获取流程部署的id
        //根据部署id查询流程定义
        BusBpmnInfo busBpmnInfo = busBpmnInfoMapper.selectBusBpmnInfoById(id);

        //根据部署的key,和版本号删除
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(busBpmnInfo.getProcessDefinitionKey())
                .processDefinitionVersion(busBpmnInfo.getVersion().intValue())
                .singleResult();
        //根据部署id删除
        repositoryService.deleteDeployment(processDefinition.getDeploymentId(),true);
        return busBpmnInfoMapper.deleteBusBpmnInfoById(id);
    }


    @Override
    @Transactional
    public int saveBusBpmn(BusBpmnInfo busBpmnInfo, InputStream inputStream) {
        //调用Activiti API定义流程
        String bpmnLabel = busBpmnInfo.getBpmnLabel();          //获取文件名
        Assert.state(bpmnLabel.endsWith("bpmn"),"文件格式不支持");
        Deployment deploy = repositoryService.createDeployment()    //部署流程获取到流程对象
                .addInputStream(bpmnLabel, inputStream)
                .deploy();
        //根据部署id查询流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .singleResult();
        //往bpmnInfo表中存入数据
        busBpmnInfo.setDeployTime(new Date());
        busBpmnInfo.setProcessDefinitionKey(processDefinition.getKey());              //activity流程定义生成的key
        busBpmnInfo.setVersion((long)processDefinition.getVersion());                           //版本号
        //存储数据
        return busBpmnInfoMapper.insertBusBpmnInfo(busBpmnInfo);
    }

    @Override
    public InputStream getInputStream(Long id, String type) {

        //根据部署id查询流程定义
        BusBpmnInfo busBpmnInfo = busBpmnInfoMapper.selectBusBpmnInfoById(id);

        //根据部署的key,和版本号查询出部署对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(busBpmnInfo.getProcessDefinitionKey())
                .processDefinitionVersion(busBpmnInfo.getVersion().intValue())
                .singleResult();
        Assert.notNull(processDefinition,"文件不存在");

        if ("xml".equals(type)) {
            return repositoryService.getProcessModel(processDefinition.getId());
            //return repositoryService.getResourceAsStream(processDefinition.getDeploymentId(),busBpmnInfo.getBpmnLabel());
        }
        // 查看流程图
        //在内存中画图对象
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        //bpmnModel对象用来封装画的流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
        return generator.generateDiagram(bpmnModel,
                new ArrayList<>(),
                Collections.emptyList(),
                "宋体",
                "宋体",
                "宋体");
    }
}
